﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BingWallpaper
{

    class BingWallpaper
    {
        public static string Url => "https://cn.bing.com";
        public static string Api1 => Url + "/HPImageArchive.aspx?idx=0&n=7";  //前7个
        public static string Api2 => Url + "/HPImageArchive.aspx?idx=7&n=8";  //后8个

        private int _index = 0;
        public int Index
        {
            get { return _index; }
            set
            {
                _index = value < 0 ? 0 : value >= DataList.Count ? DataList.Count - 1 : value;
            }
        }
        public int Count => DataList.Count;
        public Data CurrentData => Count > 0 ? DataList[Index] : null;

        List<Data> DataList { get; set; } = new List<Data>();

        public BingWallpaper()
        {
            //安全协议
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            //获取两个API数据
            DataList = GetImageDatas(Api1).Concat(GetImageDatas(Api2)).ToList();
            //下载所有图片
            DataList.AsParallel().ForAll(data => data.GetImageFile());
        }

        private IEnumerable<Data> GetImageDatas(string url)
        {
            try
            {
                var xe1 = XElement.Load(url);
                return xe1.Descendants("image").Select(x => new Data
                {
                    Startdate = x.Element("startdate")?.Value,
                    Fullstartdate = x.Element("fullstartdate")?.Value,
                    Enddate = x.Element("enddate")?.Value,
                    Url = x.Element("url")?.Value,
                    Urlbase = x.Element("urlBase")?.Value,
                    Copyright = x.Element("copyright")?.Value,
                    Copyrightlink = x.Element("copyrightlink")?.Value,
                    Headline = x.Element("headline")?.Value,
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return new List<Data>(); //返回空列表
            }
        }


        public override bool Equals(object obj)
        {
            try
            {
                if (obj is BingWallpaper bw)
                {
                    return DataList.First().Startdate == bw.DataList.First().Startdate;
                }
            }
            catch (Exception)
            {
                //
            }
            return false;
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

    }
}
